package com.example.bluetoothtest;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.VpnManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.PrecomputedText;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.text.PrecomputedTextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.tabs.TabLayout;

import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;

public class MainActivity2 extends AppCompatActivity {

    // 新增成员变量
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothSocket bluetoothSocket;
    private String deviceAddress;
    private String deviceName;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private Button start_test;
    private EditText test_time, dis_time, wait_time;
    private TextView textView;
    //存储当前线程
    private Thread currentThread;

    private BluetoothProfile a2dpProfile;
    private BluetoothProfile hfpProfile;
    private BluetoothDevice bluetoothDevice;

    private Handler handler = new Handler();

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main2);

        deviceName = getIntent().getStringExtra("bluetooth_name");
        //存储MAC地址
        deviceAddress = getIntent().getStringExtra("bluetooth_address");
        ((TextView) findViewById(R.id.device_name)).setText("设备名称：" + deviceName + "\n" + "MAC地址：" + deviceAddress);

        // 新增初始化
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //控件初始化
        // 开始按键
        start_test = findViewById(R.id.start_test);
        //次数
        test_time = findViewById(R.id.test_times);
        //断连时间
        dis_time = findViewById(R.id.dis_times);
        //间隔时间
        wait_time = findViewById(R.id.wait_times);
        //日志textview
        textView = findViewById(R.id.tv_log);
        textView.setText(textView.getText(), TextView.BufferType.EDITABLE);
        textView.setMovementMethod(new ScrollingMovementMethod());

        //设置默认值
        test_time.setText("50");
        dis_time.setText("5");
        wait_time.setText("10");

        //按钮点击事件
        start_test.setOnClickListener(v -> ConnectAndDisconnect());

        //注册广播接收器
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothReceiver, filter);
        //初始化 A2DP 和 HFP配置文件
        bluetoothAdapter.getProfileProxy(this, a2dpProfileListener, BluetoothProfile.A2DP);
        bluetoothAdapter.getProfileProxy(this, hfpProfileListener, BluetoothProfile.HEADSET);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 终止当前线程
        if (currentThread != null && currentThread.isAlive()) {
            currentThread.interrupt();
            try {
                currentThread.join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                Log.e("TEST", "线程中断", e);
            }
        }
        disconnectDevice(() -> {
        });

        // 取消注册广播接收器
        unregisterReceiver(bluetoothReceiver);

        // 关闭 A2DP 和 HFP 配置文件代理
        if (a2dpProfile != null) {
            bluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, a2dpProfile);
            a2dpProfile = null;
        }
        if (hfpProfile != null) {
            bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, hfpProfile);
            hfpProfile = null;
        }
    }

    // 连接逻辑
    @SuppressLint("MissingPermission")
    private void connectDevice(Runnable onSuccess) {
        new Thread(() -> {
            if (bluetoothDevice == null) {
                Log.e("Bluetooth", "蓝牙设备为空");
                runOnUiThread(() -> {
                    Toast.makeText(this, "蓝牙设备为空", Toast.LENGTH_LONG).show();
                    updateUI(false);
                });
                return;
            }

            if ((a2dpProfile != null && a2dpProfile instanceof BluetoothA2dp) && (hfpProfile != null && hfpProfile instanceof BluetoothHeadset)) {
                BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) a2dpProfile;
                BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
                try {
                    // 使用反射调用隐藏的 connect 方法
                    Method connectMethod = BluetoothA2dp.class.getMethod("connect", BluetoothDevice.class);
                    connectMethod.invoke(bluetoothA2dp, bluetoothDevice);
                    Log.d("Bluetooth", "A2DP 连接请求已发送");
                    // 使用反射调用隐藏的 connect 方法
                    Method connectMethod1 = BluetoothHeadset.class.getMethod("connect", BluetoothDevice.class);
                    connectMethod1.invoke(bluetoothHeadset, bluetoothDevice);
                    Log.d("Bluetooth", "HFP 连接请求已发送");
                } catch (Exception e) {
                    Log.e("Bluetooth", "无法调用 A2DP或HFP 的 connect 方法", e);
                }
            }

//            if (hfpProfile != null && hfpProfile instanceof BluetoothHeadset) {
//                BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
//                try {
//                    // 使用反射调用隐藏的 connect 方法
//                    Method connectMethod = BluetoothHeadset.class.getMethod("connect", BluetoothDevice.class);
//                    connectMethod.invoke(bluetoothHeadset, bluetoothDevice);
//                    Log.d("Bluetooth", "HFP 连接请求已发送");
//                } catch (Exception e) {
//                    Log.e("Bluetooth", "无法调用 HFP 的 connect 方法", e);
//                }
//            }

            runOnUiThread(() -> {
//                updateUI(true); // 更新UI
                if (onSuccess != null) onSuccess.run();
            });
        }).start();
    }
//    private void connectDevice(Runnable onSuccess) {
//        new Thread(() -> {
//            try {
//                // 验证设备地址有效性
//                if (!BluetoothAdapter.checkBluetoothAddress(deviceAddress)) {
//                    throw new IllegalArgumentException("无效设备地址");
//                }
//                BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
//                bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
//                bluetoothSocket.connect();
//                runOnUiThread(() -> {
//                    updateUI(true); // 更新UI
//                    if (onSuccess != null) onSuccess.run();
//                });
////                runOnUiThread(() -> {
////                    Toast.makeText(this, "成功连接：" + deviceName, Toast.LENGTH_SHORT).show();
////                });
//            } catch (Exception e) {
//                Log.e("BT_CONNECT", "连接失败: " + e.getMessage());
//                runOnUiThread(() -> {
//                    Toast.makeText(this, "连接失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
//                    updateUI(false);
//                });
//            }
//        }).start();
//    }

    //    更新UI
    private void updateUI(boolean isConnected) {
        new Thread(() -> {
            try {
                runOnUiThread(() -> {
                    Editable editable = (Editable) textView.getText();
                    runOnUiThread(() -> {
                        editable.append(isConnected ? "已连接\n" : "断开连接\n");
                    });
                    scrollToBottom();
                });
            } catch (NullPointerException e) {
                Log.e("UI_UPDATE", "控件未初始化: " + e.getMessage());
            }
        }).start();
    }

    private void updateUI(int i, int total_times) {
        new Thread(() -> {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(new java.util.Date());
                runOnUiThread(() -> {
                    Editable editable = (Editable) textView.getText();
                    runOnUiThread(() -> {
                        editable.append(formattedDate + " [" + i + "/" + total_times + "]\n");
                    });
                    scrollToBottom();
                });
            } catch (NullPointerException e) {
                Log.e("UI_UPDATE", "控件未初始化: " + e.getMessage());
            }
        }).start();
    }

    // 断开连接(带回调)
    @SuppressLint("MissingPermission")
    private void disconnectDevice(Runnable onSuccess) {
        if (bluetoothDevice == null) {
            Log.e("Bluetooth", "蓝牙设备为空");
            runOnUiThread(() -> {
                Toast.makeText(this, "蓝牙设备为空", Toast.LENGTH_LONG).show();
                updateUI(false);
            });
            return;
        }

        // 断开 A2DP&HFP 连接
        if ((a2dpProfile != null && a2dpProfile instanceof BluetoothA2dp) && (hfpProfile != null && hfpProfile instanceof BluetoothHeadset)) {
            BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) a2dpProfile;
            BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
            try {
                Method disconnectMethod = BluetoothA2dp.class.getMethod("disconnect", BluetoothDevice.class);
                disconnectMethod.invoke(bluetoothA2dp, bluetoothDevice);
                Log.d("Bluetooth", "A2DP 断开请求已发送");
                Method disconnectMethod1 = BluetoothHeadset.class.getMethod("disconnect", BluetoothDevice.class);
                disconnectMethod1.invoke(bluetoothHeadset, bluetoothDevice);
                Log.d("Bluetooth", "HFP 断开请求已发送");
            } catch (Exception e) {
                Log.e("Bluetooth", "无法调用 A2DP或HFP 的 disconnect 方法", e);
            }
        }

        // 断开 HFP 连接
//        if (hfpProfile != null && hfpProfile instanceof BluetoothHeadset) {
//            BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) hfpProfile;
//            try {
//                Method disconnectMethod = BluetoothHeadset.class.getMethod("disconnect", BluetoothDevice.class);
//                disconnectMethod.invoke(bluetoothHeadset, bluetoothDevice);
//                Log.d("Bluetooth", "HFP 断开请求已发送");
//            } catch (Exception e) {
//                Log.e("Bluetooth", "无法调用 HFP 的 disconnect 方法", e);
//            }
//        }

        runOnUiThread(() -> {
//            updateUI(false);
            if (onSuccess != null) onSuccess.run();
        });
    }
//    private void disconnectDevice(Runnable onSuccess) {
//        new Thread(() -> {
//            try {
//                if (bluetoothSocket != null) {
//                    bluetoothSocket.close();
//                    bluetoothSocket = null;
//                    runOnUiThread(() -> {
//                        updateUI(false);
//                        if (onSuccess != null) onSuccess.run();
//                    });
//                }
//            } catch (IOException e) {
//                Log.e("Bluetooth", "断开连接失败", e);
//            }
//        }).start();
//    }

    private void ConnectAndDisconnect() {
        //获取测试次数
        String get_times = test_time.getText().toString().trim();
        //获取间隔时间
        String w_time = wait_time.getText().toString().trim();
        //获取断连时间
        String d_time = dis_time.getText().toString().trim();
        int defaultTimes = 2000;
        if (!get_times.isEmpty()) {
            try {
                int g_times = validateInput(get_times, "测试次数");
                int dc_time = d_time.isEmpty() ? defaultTimes : validateInput(d_time, "断连时间") * 1000;
                int wa_time = w_time.isEmpty() ? defaultTimes : validateInput(w_time, "间隔时间") * 1000;
                //终止旧线程
                if (currentThread != null && currentThread.isAlive()) {
                    currentThread.interrupt();
                    try {
                        currentThread.join();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        Log.e("TEST", "线程中断", e);
                    }
                }
                //开启线程，避免运行循环时主线程卡死
                currentThread = new Thread(() -> {
                    textView.setText("");
                    scrollToBottom();
                    for (int i = 1; i <= g_times; i++) {
                        final int currentIteration = i;
                        runOnUiThread(() -> {
                            updateUI(currentIteration, g_times);
                        });
                        runOnUiThread(() -> connectDevice(() -> {
                            //连接成功后的逻辑
                            Log.d("TEST", "第 " + currentIteration + "次连接成功");
                            //延迟后断开
                            new Thread(() -> {
                                try {
                                    Thread.sleep(dc_time);
                                    runOnUiThread(() -> disconnectDevice(() -> {
                                        Log.d("TEST", "第 " + currentIteration + "次断开成功");
                                    }));
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt();
                                    Log.e("TEST", "线程中断", e);
                                }
                            }).start();
                        }));

                        //等待本次连接-断开完成
                        try {
                            Thread.sleep(wa_time);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            Log.e("TEST", "线程中断", e);
                        }

                        //检查线程是否被中断
                        if (Thread.currentThread().isInterrupted()) {
                            Log.d("TEST", "线程被中断，提前结束");
                            break;
                        }
                    }
                    runOnUiThread(() -> {
                        Toast.makeText(this, "执行 " + g_times + " 次结束", Toast.LENGTH_SHORT).show();
                    });
                });
                currentThread.start();
            } catch (IllegalArgumentException e) {
                runOnUiThread(() -> {
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }
    }

    // 验证输入是否为正整数
    private int validateInput(String input, String fieldName) throws IllegalArgumentException {
        if (input.matches("\\d+") && Integer.parseInt(input) > 0) {
            return Integer.parseInt(input);
        } else {
            throw new IllegalArgumentException(fieldName + " 必须是正整数");
        }
    }


    // 日志滚动到底部方法
    private void scrollToBottom() {
        textView.post(() -> {
            int offset = textView.getLineCount() * textView.getLineHeight();
            if (offset > textView.getHeight()) {
                textView.scrollTo(0, offset - textView.getHeight());
            }
        });
    }

    // 广播接收器
    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                Log.d("Bluetooth", "设备已连接: " + device.getName());
                runOnUiThread(() -> updateUI(true));
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                Log.d("Bluetooth", "设备已断开: " + device.getName());
                runOnUiThread(() -> updateUI(false));
            }
        }
    };

    // A2DP 配置文件监听器
    private final BluetoothProfile.ServiceListener a2dpProfileListener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.A2DP) {
                a2dpProfile = proxy;
                // 将代理转换为具体的 A2DP 类型
                BluetoothA2dp bluetoothA2dp = (BluetoothA2dp) proxy;
                @SuppressLint("MissingPermission") Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                for (BluetoothDevice device : pairedDevices) {
                    if (device.getAddress().equals(deviceAddress)) {
                        bluetoothDevice = device;
                        break;
                    }
                }
            }
        }

        @Override
        public void onServiceDisconnected(int profile) {
            a2dpProfile = null;
        }
    };

    // HFP 配置文件监听器
    private final BluetoothProfile.ServiceListener hfpProfileListener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.HEADSET) {
                hfpProfile = proxy;
                // 将代理转换为具体的 HFP 类型
                BluetoothHeadset bluetoothHeadset = (BluetoothHeadset) proxy;
            }
        }

        @Override
        public void onServiceDisconnected(int profile) {
            hfpProfile = null;
        }
    };

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        disconnectDevice(() -> {});
//    }

}